/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hextd.core;

import hextd.map.GameMapImplementation;
import com.twolattes.json.Json;
import com.twolattes.json.Marshaller;
import com.twolattes.json.TwoLattes;
import java.lang.ref.WeakReference;
import com.usoog.tdcore.map.GameMap;
import com.usoog.tdcore.map.MapInfo;

/**
 *
 * @author hylke
 */
public class MapInfoImplementation extends MapInfo {

	private WeakReference<GameMapImplementation> mapDataCache;
	private static Marshaller<GameMapImplementation> marshaller;

	@Override
	public void setContent(String newContent) {
		super.setContent(newContent);
		mapDataCache = null;
	}

	@Override
	public GameMap getMapData() {
		String content = getContent();
		if (content != null) {
			GameMapImplementation mapData = null;
			if (mapDataCache != null) {
				mapData = mapDataCache.get();
			}
			if (mapData == null) {
				if (marshaller == null) {
					marshaller = TwoLattes.createMarshaller(GameMapImplementation.class);
				}
				try {
					Json.Value fromString = Json.fromString(content);
					mapData = marshaller.unmarshall((Json.Object) fromString);
				} catch (ClassCastException e) {
					System.out.println("MapInfo::getMapData: Not a valid JSon map!");
				} catch (IllegalArgumentException e) {
					System.out.println("MapInfo::getMapData: Not a valid JSon map!");
				}
				mapDataCache = new WeakReference<GameMapImplementation>(mapData);
				players = mapData.players.size();
				title = mapData.getTitle();
			}
			return mapData;
		} else {
			return null;
		}

	}
}
